<template>
  <div class="app-container">
    <el-form ref="form" :model="params" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="6">
          <el-form-item prop="appName" :label="$t('permission.applicationName')">
            <el-input v-model.trim="params.appName" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="AppId" prop="appId">
            <el-input v-model.trim="params.appId" />
          </el-form-item>
        </el-col>
        <el-col :span="5" style="text-align: center">
          <el-button type="primary" @click="search('form')">{{ $t('btn.query') }}</el-button>
          <el-button type="danger" @click="reset('form')">{{ $t('btn.reset') }}</el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-button v-permission="'gaeaSettingController#insert'" type="primary" icon="el-icon-plus" @click="showAddLogModel('新增')">{{ $t('btn.add') }}</el-button>
    <delete-btn v-permission="'gaeaSettingController#deleteById'" :disabled="selectedList.length < 1 || selectedList.length > 1" @handleDelete="handleDelete" />
    <el-button v-permission="'gaeaUserController#resetPassword'" type="warning" icon="el-icon-warning" :disabled="selectedList.length != 1" @click="resetPsw">{{ $t('permission.Resetkey') }}</el-button>
    <!-- 查询结果列表 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" style="width: 100%" border fit highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="expand">
        <template slot-scope="props">
          <div class="table-expand-item">
            <div class="appList-fen">
              <span class="titel">{{ $t('permission.applicationName') }}: </span>
              <span>{{ props.row.appName }}</span>
            </div>
            <div class="appList-fen">
              <span class="titel">AppId: </span>
              <span>{{ props.row.appId }}</span>
            </div>
          </div>
          <div class="table-expand-item">
            <div class="appList-fen">
              <span class="titel">{{ $t('permission.ApplicationPrivateKey') }}: </span>
              <span>{{ props.row.appSecret }}</span>
            </div>
            <div class="appList-fen">
              <span class="titel">{{ $t('businessGlossary.creator') }}: </span>
              <span>{{ props.row.createBy }}</span>
            </div>
          </div>
          <div class="table-expand-item">
            <div class="appList-fen">
              <span class="titel">{{ $t('businessGlossary.creationTime') }}: </span>
              <span>{{ props.row.createTime }}</span>
            </div>
            <div class="appList-fen">
              <span class="titel">{{ $t('interface.updateUser') }}: </span>
              <span>{{ props.row.updateBy }}</span>
            </div>
          </div>
          <div class="table-expand-item">
            <div class="appList-fen">
              <span class="titel">{{ $t('apiList.updateTime') }}: </span>
              <span>{{ props.row.updateTime }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed type="selection" width="50" center />
      <el-table-column :label="$t('permission.applicationName')" max-width="120" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.appName }}
        </template>
      </el-table-column>
      <el-table-column label="AppId" min-width="110" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.appId }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('permission.ApplicationPrivateKey')" min-width="160" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.appSecret }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('interface.status')" min-width="130" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.statusName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('businessGlossary.creator')" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.createBy }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('businessGlossary.creationTime')" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('interface.updateUser')" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.updateBy }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('apiList.updateTime')" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.updateTime }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.operation')" width="160px" align="center">
        <template slot-scope="scope">
          <el-button size="mini" style="margin-right: 2px" type="text" @click="openCallNumber(scope.row)">接口列表</el-button>
          <el-button size="mini" style="margin-right: 2px" type="text" @click="showAddLogModel(scope.row)"> {{ $t('table.edit') }} </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <el-pagination v-show="total > 0" background :current-page.sync="params.pageNumber" :page-sizes="$pageSizeAll" :page-size="params.pageSize" layout="total, prev, pager, next, jumper, sizes" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <el-dialog :title="dailogName" width="50%" :close-on-click-modal="false" center :visible.sync="basicDialog" @close="closeDialog">
      <el-form ref="userForm" :model="dialogForm" :rules="formRules" label-width="140px">
        <el-row class="form_table">
          <el-col :span="24">
            <el-form-item :label="$t('permission.applicationName')" prop="appName">
              <el-input v-model.trim="dialogForm.appName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="form_table">
          <el-col :span="24">
            <el-form-item label="appId" prop="appId">
              <el-input v-model="dialogForm.appId" :disabled="appIdStatus" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="form_table">
          <el-col :span="24">
            <el-form-item :label="$t('interface.status')" prop="status">
              <el-select v-model="dialogForm.status" clearable="clearable" filterable value-key="id" :placeholder="$t('table.pleaseSelect')">
                <el-option v-for="item in appStatus" :key="item.id" :label="item.text" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="form_table">
          <el-col :span="24">
            <el-form-item :label="$t('interface.ApplicationDescription')" prop="remark">
              <el-input v-model="dialogForm.remark" type="textarea" rows="4" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" style="text-align: center">
        <el-button type="primary" @click="dailogName === '新增' ? confirmAdd() : confirm()">{{ $t('btn.confirmP') }}</el-button>
        <el-button @click="cancelFunction()">{{ $t('table.cancel') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="callNumberDialog.title" width="80%" :close-on-click-modal="false" center :visible.sync="callNumberDialog.dialog">
      <el-table :data="callNumberDialog.list" border style="width: 100%">
        <el-table-column prop="appId" label="应用ID" />
        <el-table-column prop="appName" label="应用名称" />
        <el-table-column prop="infName" label="接口标识" />
        <el-table-column prop="infNameName" label="接口名称" />
        <el-table-column prop="times" label="剩余调用次数">
          <template slot-scope="props">
            <el-input-number v-model.number="props.row.times" controls-position="right" :min="0" :step="1" step-strictly />
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" style="text-align: center">
        <el-button type="primary" @click="submitCallNumber">{{ $t('btn.save') }}</el-button>
        <el-button @click="callNumberDialog.dialog = false">{{ $t('table.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageList, businessApplication, addApplication, deleteApplication, appSecret, queryListInfApp, updateTimes } from '@/api/generator/application'
import { getDictList } from '@/api/dict-data'
export default {
  data() {
    return {
      callNumberDialog: {
        dialog: false,
        list: [],
        title: '接口列表',
      },
      total: 1,
      appIdStatus: false,
      confirmStatus: false,
      selectedList: [],
      appStatus: [],
      rules: {
        requestUrl: [{ required: false, message: this.$t('placeholder.input'), trigger: 'blur' }],
        pageTitle: [{ required: false, message: this.$t('placeholder.input'), trigger: 'blur' }],
        userName: [{ required: false, message: this.$t('placeholder.input'), trigger: 'blur' }],
      },
      params: {
        pageNumber: 1,
        pageSize: 10,
        appId: '',
        sort: 'update_time',
        order: 'DESC',
      },
      list: null,
      totalCount: 0,
      totalPage: 0,
      listLoading: true,
      // 项目基础配置
      basicDialog: false,
      dailogName: '',
      dialogForm: {
        appId: '',
        appName: '',
        status: '',
        remark: '',
      },
      formRules: {
        appId: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
        appName: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
        status: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
        remark: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
      },
    }
  },
  created() {
    this.queryByPage()
    getDictList('ENABLE_FLAG').then(({ data }) => {
      this.appStatus = data
    })
  },
  methods: {
    submitCallNumber() {
      const params = this.callNumberDialog.list.map((item) => {
        return {
          id: item.id,
          times: item.times,
        }
      })
      updateTimes(params).then((res) => {
        this.callNumberDialog.dialog = false
      })
    },
    openCallNumber(row) {
      queryListInfApp({ appId: row.appId }).then((res) => {
        this.callNumberDialog.list = res.data || []
        this.callNumberDialog.dialog = true
      })
    },
    cancelFunction() {
      this.queryByPage()
      this.basicDialog = false
    },
    // 重置密钥
    async resetPsw() {
      const ids = this.selectedList.map((item) => item.id)
      const { code } = await appSecret(ids)
      // const { code } = await deleteUser(this.selectedList[0].id) // 暂时保留单删接口
      if (code != '200') return
      this.queryByPage()
    },
    // 选择项改变时
    handleSelectionChange(val) {
      this.selectedList = val
    },
    // 删除操作
    async handleDelete() {
      const ids = this.selectedList.map((item) => item.id)
      const { code } = await deleteApplication(ids)
      // const { code } = await deleteUser(this.selectedList[0].id) // 暂时保留单删接口
      if (code != '200') return
      this.queryByPage()
    },
    // 查询
    search(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('submit!')
          this.params.pageNumber = 1
          this.queryByPage()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 重置
    reset(formName) {
      this.$refs[formName].resetFields()
      this.params.userName = ''
      this.params.pageTitle = ''
      this.params.requestUrl = ''
      this.queryByPage()
    },
    async queryByPage() {
      const res = await pageList(this.params)
      if (res.code != '200') return
      this.listLoading = true
      this.list = res.data.records
      this.total = res.data.total
      this.listLoading = false
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.queryByPage()
    },
    handleCurrentChange(val) {
      this.params.pageNumber = val
      this.queryByPage()
    },
    // 关闭模态框
    closeDialog(bool) {
      // bool && this.search('form') // 点确定关闭弹窗的时候才会刷新列表
      this.queryByPage()
      this.$refs['userForm'].resetFields()
      this.basicDialog = false
    },
    // 打开模态框
    showAddLogModel(val) {
      this.basicDialog = true
      if (val == '新增') {
        this.dailogName = '新增'
        this.appIdStatus = false
        this.confirmStatus = true
        this.dialogForm = {}
      } else {
        this.confirmStatus = false
        this.dailogName = '编辑'
        this.appIdStatus = true
        this.dialogForm = val
        this.dialogForm.name = val.name
        this.dialogForm.code = val.code
        this.dialogForm.status = val.status.toString()
        this.$forceUpdate()
      }
    },
    // 新增按钮
    confirmAdd() {
      this.$refs.userForm.validate(async(valid, obj) => {
        if (valid) {
          const { code } = await addApplication(this.dialogForm)
          if (code != '200') return
          this.closeDialog(true)
        } else {
          return
        }
      })
    },
    // 提交按钮
    confirm() {
      this.$refs.userForm.validate(async(valid, obj) => {
        if (valid) {
          const { code } = await businessApplication(this.dialogForm)
          if (code != '200') return
          this.closeDialog(true)
        } else {
          return
        }
      })
    },
  },
}
</script>
<style scoped lang="scss">
.header {
  line-height: 40px;
  font-weight: bold;
  text-indent: 3rem;
  background: #f9fcff;
  margin-bottom: 5px;
}
.appList-fen {
  width: 50%;
  float: left;
  line-height: 24px;
}
</style>
